package per.destiny.seckill.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import per.destiny.seckill.pojo.User;
import per.destiny.seckill.vo.RespBean;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

public class UserUtils {

    public static void main(String[] args) throws Exception {
        createUser(1000);
    }

    private static void createUser(int count) throws Exception {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            User user = new User();
            user.setNickname("user:" + i);
            user.setSalt("1a2b3c4d");
            user.setPassword(MD5Utils.inputPassToDBPass("asdasd", user.getSalt()));
            user.setMobile(String.valueOf(13000000000L + i));
            users.add(user);
        }
        System.out.println("create user");
        Connection connection = getConn();
        String sql = "insert into t_user(nickname,salt,password,mobile) values (?,?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (User user : users) {
            preparedStatement.setString(1, user.getNickname());
            preparedStatement.setString(2, user.getSalt());
            preparedStatement.setString(3, user.getPassword());
            preparedStatement.setString(4, user.getMobile());
            preparedStatement.addBatch();
        }
        preparedStatement.executeBatch();
        preparedStatement.clearParameters();
        connection.close();
        System.out.println("insert to db");

        // 登录，生成userTicket
        String urlString = "http://localhost:8080/login/doLogin";
        File file = new File("C:\\Users\\MI\\Desktop\\config.txt");
        if (file.exists()) {
            file.delete();
        }
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        randomAccessFile.seek(0);
        for (User user : users) {
            URL url = new URL(urlString);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
            httpURLConnection.setRequestProperty("accept", "application/json");
            OutputStream outputStream = httpURLConnection.getOutputStream();
            String params = "{\"mobile\":\"%s\",\"password\":\"%s\"}";
            outputStream.write(String.format(params, user.getMobile(), MD5Utils.inputPassToFormPass("asdasd")).getBytes());
            outputStream.flush();
            InputStream inputStream = httpURLConnection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) >= 0) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            inputStream.close();
            byteArrayOutputStream.close();
            String response = new String(byteArrayOutputStream.toByteArray());
            System.out.println("response is " + response);
            ObjectMapper objectMapper = new ObjectMapper();
            RespBean respBean = objectMapper.readValue(response, RespBean.class);
            String userTicket = (String) respBean.getObj();
            System.out.println("create userTicket:" + userTicket);
            String row = user.getMobile() + "," + userTicket;
            randomAccessFile.seek(randomAccessFile.length());
            randomAccessFile.write(row.getBytes());
            randomAccessFile.write("\r\n".getBytes());
            System.out.println("write to file:" + user.getMobile());
        }
    }

    private static Connection getConn() throws Exception {
        String url = "jdbc:mysql://hadoop100:3306/seckill?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "asdasd";
        String driver = "com.mysql.cj.jdbc.Driver";
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }

}
